package com.ias.agdis_r.fragment.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import androidx.fragment.app.Fragment;
//import android.support.v4.app.FragmentActivity;
import androidx.fragment.app.FragmentActivity;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.flight.SearchDetailActivity;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.util.SecurityUtil;
import com.ias.agdis_r.util.sdcard.WriteLog;
import com.sleepbot.datetimepicker.time.RadialPickerLayout;
import com.sleepbot.datetimepicker.time.TimePickerDialog;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Flight extends Fragment implements TimePickerDialog.OnTimeSetListener {
	private Context context = DataBaseManager.getInstance().getContext();

	/** 服务器时间格式 */
	@SuppressLint("SimpleDateFormat")
	private final SimpleDateFormat SERVER_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private final String KEY_LAST_EDITOR_VAL = "FLIGHT_INPUT_VAL_KEY";
	private String flno=context.getString(R.string.flno);
	private String regnumber=context.getString(R.string.regnumber);
	private String placecode=context.getString(R.string.placecode);
	private String blt=context.getString(R.string.blt);
	private String gat=context.getString(R.string.gat);

	/** 查询条件可选项 */
	private final String SELECT_LEVEL_1[] = new String[] {flno, regnumber, placecode,blt, gat};
	/** 过滤条件可选项 */
	private final String SELECT_LEVEL_2[] = { context.getString(R.string.all), context.getString(R.string.adid_a), context.getString(R.string.adid_d) };

	private final String AOD_MAP[] = new String[] { "null", "A", "D" };
	public final String TIMEPICKER_TAG1 = "starttime";

	public final String TIMEPICKER_TAG2 = "endtime";

	private SharedPreferences preferences;

	/** 查询条件与对应字段的映射关系 */
	private Map<String, String> queryKeys = new HashMap<String, String>();

	/** 时间选择区域 */
	private LinearLayout timeSelectPanel;

	private TextView startime, endtime;
	private Button searchbtn;
	private EditText searchInfo;

	private Spinner spinner1, spinner2;
	private CheckBox checkAgent;
	private CheckBox checkToday;
	private CheckBox checkAccurate;

	private TimePickerDialog starttimePickerDialog, endtimePickerDialog;
	private Calendar calendar_start = Calendar.getInstance(), calendar_end = Calendar.getInstance();
	private Calendar calendar_today_start = Calendar.getInstance(),calendar_today_end = Calendar.getInstance();

	private boolean hideTodayFlight = JavaBeanManager.getInstance().isHideTodayFlight();
	private String TodayTime = JavaBeanManager.getInstance().getTodayFlightTime();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.activity_flight, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		preferences = getActivity().getPreferences(Activity.MODE_PRIVATE);

		queryKeys.put(flno, "fln");
		queryKeys.put(regnumber, "reg");
		queryKeys.put(placecode, "placecode");
		queryKeys.put(blt, "blt");
		queryKeys.put(gat, "gat");

		initCalendar();
		initView(view);
		initEvents();
		initTimeEvent(view);

	}

	/**
	 * 初始化时间以及时间选择对话框
	 */
	private void initCalendar() {
//		calendar_start = Calendar.getInstance();
//		calendar_end = Calendar.getInstance();
//		if (calendar_start.get(Calendar.HOUR_OF_DAY) > 1) {
//			calendar_start.add(Calendar.HOUR_OF_DAY, -1);
//		} else {
//			calendar_start.set(Calendar.MINUTE, 0);
//		}
//		calendar_end.add(Calendar.HOUR_OF_DAY, 2);

		starttimePickerDialog = TimePickerDialog.newInstance(this, calendar_start.get(Calendar.HOUR_OF_DAY),
				calendar_start.get(Calendar.MINUTE), false, false);
		endtimePickerDialog = TimePickerDialog.newInstance(this, calendar_end.get(Calendar.HOUR_OF_DAY),
				calendar_end.get(Calendar.MINUTE), false, false);
	}

	private void resetCalendar(){
        calendar_start.clear();
        calendar_end.clear();
		calendar_start = Calendar.getInstance();
		calendar_end = Calendar.getInstance();
		if (calendar_start.get(Calendar.HOUR_OF_DAY) > 1) {
			calendar_start.add(Calendar.HOUR_OF_DAY, -1);
		} else {
			calendar_start.set(Calendar.MINUTE, 0);
		}
		calendar_end.add(Calendar.HOUR_OF_DAY, 3);
		starttimePickerDialog.setStartTime(calendar_start.get(Calendar.HOUR_OF_DAY),
				calendar_start.get(Calendar.MINUTE));
		endtimePickerDialog.setStartTime(calendar_end.get(Calendar.HOUR_OF_DAY),
				calendar_end.get(Calendar.MINUTE));
		validateTimeView();
	}

	private void initEvents() {

		searchbtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				query();
			}
		});

		searchInfo.setOnEditorActionListener(new TextView.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				query();
				return true;
			}
		});

		spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				String text = arg0.getItemAtPosition(arg2).toString();
				if (text.equals(placecode) || text.equals(blt) || text.equals(gat)) {
					timeSelectPanel.setVisibility(View.VISIBLE);
					checkToday.setVisibility(View.INVISIBLE);
					checkAccurate.setVisibility(View.GONE);
					resetCalendar();
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.AF_5), false);
				}else if(text.equals(regnumber)){
					checkAccurate.setVisibility(View.GONE);
				} else {
					timeSelectPanel.setVisibility(View.GONE);
					checkAccurate.setVisibility(View.GONE);
					if (!hideTodayFlight){
						checkToday.setVisibility(View.VISIBLE);
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		});

	}

	/**
	 * 执行查询操作
	 */
	protected void query() {
		int[] unlimitArr = JavaBeanManager.getInstance().getFlightSearchUnlimit();
		String str = getResources().getString(R.string.inputError);
		if (flno.equals(spinner1.getSelectedItem())) {
			if (0 < unlimitArr[0] && searchInfo.getText().length() < unlimitArr[0]) {
				String msg = String.format(str, unlimitArr[0]);
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
				return;
			}
		} else if (regnumber.equals(spinner1.getSelectedItem())) {
			if (0 < unlimitArr[1] && searchInfo.getText().length() < unlimitArr[1]) {
				String msg = String.format(str, unlimitArr[1]);
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
				return;
			}
		} else if (placecode.equals(spinner1.getSelectedItem())) {
			if (0 < unlimitArr[2] && searchInfo.getText().length() < unlimitArr[2]) {
				String msg = String.format(str, unlimitArr[2]);
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
				return;
			}
		} else if (blt.equals(spinner1.getSelectedItem())) {
			if (0 < unlimitArr[3] && searchInfo.getText().length() < unlimitArr[3]) {
				String msg = String.format(str, unlimitArr[3]);
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
				return;
			}
		} else if (gat.equals(spinner1.getSelectedItem())) {
			if (0 < unlimitArr[4] && searchInfo.getText().length() < unlimitArr[4]) {
				String msg = String.format(str, unlimitArr[4]);
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
				return;
			}
		}

		// 准备参数
		Map<String, Object> requestBody = new HashMap<String, Object>();
		Map<String, String> header = SecurityUtil.getCommonRequestHeader(MessageModel.QFIQ);
		Map<String, Object> flightVO = new HashMap<String, Object>();

		String key = (String) spinner1.getSelectedItem();
		flightVO.put(queryKeys.get(key), searchInfo.getText().toString());

		flightVO.put("aod", AOD_MAP[spinner2.getSelectedItemPosition()]);

		flightVO.put("idx", "0");
		flightVO.put("dir", "N");
		flightVO.put("num", SearchDetailActivity.DEFAUTL_PAGE_SIZE);

		if (checkAgent.isChecked()) {
			flightVO.put("ifa", "Y");
		}
		if (checkAccurate.getVisibility()==View.VISIBLE&&checkAccurate.isChecked()) {
			flightVO.put("islk", "N");
		}

		if (timeSelectPanel.getVisibility() == View.VISIBLE) {
			flightVO.put("ftm", SERVER_DATE_FORMAT.format(calendar_start.getTime()));
			if(calendar_start.after(calendar_end)){
				Calendar cal = Calendar.getInstance();
				cal.setTime(calendar_end.getTime());
				cal.add(Calendar.DATE, 1);
				flightVO.put("ttm", SERVER_DATE_FORMAT.format(cal.getTime()));
			}else{
				flightVO.put("ttm", SERVER_DATE_FORMAT.format(calendar_end.getTime()));
			}

		}else if(!hideTodayFlight && checkToday.isChecked()){
			if (TodayTime.length()!=4){
				TodayTime = "0000";
			}
			int hour = 0;
			int minute = 0;
			try {
				hour = Integer.parseInt(TodayTime.substring(0,2));
				minute = Integer.parseInt(TodayTime.substring(2,4));
			}catch (NumberFormatException e){
				hour = 0;
				minute = 0;
				WriteLog.getInstance().writeLog("TodayTime,NumberFormatException:"+e.getMessage());
				e.printStackTrace();
			}
			calendar_today_start.setTime(new Date());
			calendar_today_start.set(Calendar.HOUR_OF_DAY, hour);
			calendar_today_start.set(Calendar.MINUTE, minute);
			calendar_today_start.set(Calendar.SECOND,0);

			int year = calendar_today_start.get(Calendar.YEAR);
			int day = calendar_today_start.get(Calendar.DAY_OF_YEAR);

			calendar_today_end.set(Calendar.YEAR, year);
			calendar_today_end.set(Calendar.DAY_OF_YEAR, day+1);
			calendar_today_end.set(Calendar.HOUR_OF_DAY, hour);
			calendar_today_end.set(Calendar.MINUTE, minute);
			calendar_today_end.set(Calendar.SECOND, 0);

			//设置时间参数
			flightVO.put("ftm", SERVER_DATE_FORMAT.format(calendar_today_start.getTime()));
			flightVO.put("ttm", SERVER_DATE_FORMAT.format(calendar_today_end.getTime()));
		}

		requestBody.put("header", header);
		requestBody.put("flightVO", flightVO);

		// 启动查询界面
		Intent intent = new Intent(getActivity(), SearchDetailActivity.class);
		try {
			intent.putExtra(SearchDetailActivity.EXTRA_SEARCH_REQUEST_BODY_JSON_STR, DataManager.getInstance().getMapper().writeValueAsString(requestBody));
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		startActivity(intent);

	}

	private void initTimeEvent(View view) {
		// TODO Auto-generated method stub
		validateTimeView();

		startime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!starttimePickerDialog.isAdded()) {
					starttimePickerDialog.setVibrate(isVibrate());
					starttimePickerDialog.setCloseOnSingleTapMinute(isCloseOnSingleTapMinute());
					starttimePickerDialog.show(((FragmentActivity) getActivity()).getSupportFragmentManager(),
							TIMEPICKER_TAG1);
				}
			}
		});
		endtime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!endtimePickerDialog.isAdded()) {
					endtimePickerDialog.setVibrate(isVibrate());
					endtimePickerDialog.setCloseOnSingleTapMinute(isCloseOnSingleTapMinute());
					endtimePickerDialog.show(((FragmentActivity) getActivity()).getSupportFragmentManager(),
							TIMEPICKER_TAG2);
				}
			}
		});
	}

	private void initView(View view) {

		startime = (TextView) view.findViewById(R.id.flight_tv_starttime);
		endtime = (TextView) view.findViewById(R.id.flight_tv_endtime);
		searchbtn = (Button) view.findViewById(R.id.flight_searchbtn);
		searchInfo = (EditText) view.findViewById(R.id.flight_et);

		searchInfo.setText(preferences.getString(KEY_LAST_EDITOR_VAL, ""));
		searchInfo.setRawInputType(InputType.TYPE_CLASS_NUMBER);          //默认打开数字键盘
		timeSelectPanel = (LinearLayout) view.findViewById(R.id.flight_linearlayout);
		timeSelectPanel.setVisibility(View.GONE);

		spinner1 = (Spinner) view.findViewById(R.id.flight_spinner1);
		spinner2 = (Spinner) view.findViewById(R.id.flight_spinner2);
		checkAgent = (CheckBox) view.findViewById(R.id.flight_is_agent);
		checkToday = (CheckBox) view.findViewById(R.id.flight_is_today);
		checkAccurate = (CheckBox) view.findViewById(R.id.flight_is_accurate);
		checkAccurate.setVisibility(View.GONE);
		if (hideTodayFlight){
			checkToday.setVisibility(View.GONE);
		}
		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getActivity(), R.layout.flight_spinner1_item,
				SELECT_LEVEL_1);
		spinner1.setAdapter(adapter1);

		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity(), R.layout.flight_spinner1_item,
				SELECT_LEVEL_2);
		spinner2.setAdapter(adapter2);
	}

	@Override
	public void onDestroy() {
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString(KEY_LAST_EDITOR_VAL, this.searchInfo.getText().toString());
		editor.commit();
		super.onDestroy();
	}

	private boolean isVibrate() {
		return false;
	}

	private boolean isCloseOnSingleTapMinute() {
		return false;
	}

	@Override
	public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
		// TODO Auto-generated method stub
		TimePickerDialog start = (TimePickerDialog) ((FragmentActivity) getActivity()).getSupportFragmentManager()
				.findFragmentByTag(TIMEPICKER_TAG1);
		TimePickerDialog end = (TimePickerDialog) ((FragmentActivity) getActivity()).getSupportFragmentManager()
				.findFragmentByTag(TIMEPICKER_TAG2);
		if (start != null && start.equals(starttimePickerDialog)) {
			calendar_start.set(Calendar.HOUR_OF_DAY, hourOfDay);
			calendar_start.set(Calendar.MINUTE, minute);
		} else if (end != null && end.equals(endtimePickerDialog)) {
			calendar_end.set(Calendar.HOUR_OF_DAY, hourOfDay);
			calendar_end.set(Calendar.MINUTE, minute);
		}
		validateTimeView();
	}

	/**
	 * 矫正界面显示的时间值
	 */
	private void validateTimeView() {
		startime.setText(String.format("%02d", calendar_start.get(Calendar.HOUR_OF_DAY)) + ":"
				+ String.format("%02d", calendar_start.get(Calendar.MINUTE)));
		endtime.setText(String.format("%02d", calendar_end.get(Calendar.HOUR_OF_DAY)) + ":"
				+ String.format("%02d", calendar_end.get(Calendar.MINUTE)));
	}

}
